package com.kevin.Code.Array;

import java.util.Arrays;
import java.util.HashSet;

/**
 * @author Vinlee Xiao
 * @Classname SetMatrixZeroes
 * @Description Leetcode 73. 矩阵置零 中等难度
 * @Date 2021/10/31 16:07
 * @Version 1.0
 */
public class SetMatrixZeroes {

    /**
     * @param matrix
     */
    public void setZeroes(int[][] matrix) {

        int m = matrix.length;
        int n = matrix[0].length;

        //用于判断该行是否被置为0
        HashSet<Integer> rows = new HashSet<>();
        //用于判断该列是否被置为0
        HashSet<Integer> cols = new HashSet<>();

        //行 列
        for (int i = 0; i < m; i++) {

            for (int j = 0; j < n; j++) {

                //判断是否为0 将该行 该列的数全部置为0
                if (matrix[i][j] == 0) {
                    if (!rows.contains(i)) {
                        rows.add(i);
                    }

                    if (!cols.contains(j)) {
                        cols.add(j);
                    }

                }

            }

        }

        //将值更改为0
        //将所有的行置为0
        for (Integer row : rows) {
            //将该行全部置为0
            Arrays.fill(matrix[row], 0);
        }


        if (rows.size() != m) {

            for (Integer col : cols) {
                for (int j = 0; j < m; j++) {

                    matrix[j][col] = 0;
                }
            }
        }


    }


    /**
     * @param matrix
     */
    public void setZeroes1(int[][] matrix) {


        int m = matrix.length;
        int n = matrix[0].length;

        boolean[] rows = new boolean[m];
        boolean[] cols = new boolean[n];


        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {

                if (matrix[i][j] == 0) {
                    rows[i] = cols[j] = true;
                }
            }

        }

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {

                if (rows[i] || cols[j]) {
                    matrix[i][j] = 0;
                }
            }

        }
    }


}
